﻿using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;

namespace HBase {
    public class DBUtils {

       static IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddXmlFile("Conf/DataBase.config").Build();
        static DBUtils() {
            Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
        }

    public static  string   getMongodb(string key ) {
            if (string.IsNullOrWhiteSpace(key)) {
                key = "main";
            }
         return getStr(configuration ,"MongoDB_"+key);

        }

        public static string getDbName() {
            return getStr(configuration ,"dbName");

        }
      
        private static Dictionary<string, IDbConnection> connectionDict = new Dictionary<string, IDbConnection>();
        public static IDbConnection wMSConn(string key) {
          
            if (string.IsNullOrWhiteSpace(key)) {
                key = "main";
            } else {
                string[] arr=key.Split("@");
                if (arr.Length == 1) {
                    key = arr[0];
                } else {
                    key = arr[1];
                }
             
            }

            lock (configuration) {
                if (connectionDict.ContainsKey(key)) {

                    return connectionDict[key];
                }

                var conn = createConnection(key);
                connectionDict.Add(key, conn);
                return conn;
            }
          
           
        }
 

        public static IDbConnection createConnection(string key) {
      
          return openMysql(key);
          
          
        }
       
        static IDbConnection openMysql(string key) {
            string connStr = getStr (configuration,"DB_"+ key);
            var connection = new MySql.Data.MySqlClient.MySqlConnection(connStr);
            connection.Open();
            return connection;
        }

        static string getStr(IConfiguration configuration ,string key) {
            return configuration[key + ":connectionString"];
        }
       public static string getStr(  string key) {
            return configuration[key + ":value"];
        }
    }
}
